const { pool, router, resJson } = require('../connect')
const usermanageSQL = require('../db/usermanage')
const NodeRSA = require("node-rsa")//引入node-rsa，解密使用
const { _publicKey, _priKey } = require('../utils/keys')


// 解密范例
// const privateKey = new NodeRSA(_priKey) // 使用node-rsa
// privateKey.setOptions({ encryptionScheme: "pkcs1" }) // 因为vue中使用jsencrypt，jsencrypt自身使用的是pkcs1加密方案, nodejs需要修改成pkcs1
// var password = privateKey.decrypt(req.body.password, "utf8")
 
/**
 * 重置密码
 */
 router.get('/resetPass', (req, res) => {   
    let params = {
      id:req.query.id
    }
    console.log(params)
    let pass = '123456'
     const publickKey = new NodeRSA(_publicKey, { encryptionScheme: 'pkcs1' });
     const encCode = publickKey.encrypt(pass, 'base64');
     console.log(encCode)
    let _res = res;
    let _data;
    // 从连接池获取连接
    pool.getConnection((err, conn) => { //数据库链接
      conn.query(usermanageSQL.resetPass, [encCode,params.id], (e, result) => { //操作数据库
          if (e) _data = {
              code: -1,
              msg: e
          }
          
          if (result && result) {
                _data = {
                    code:0,
                    msg: '重置密码成功',
                    data: []                   
                }
                resJson(_res, _data)
          } else {
            console.log(e,result)
              _data = {
                  code: -1,
                  msg: '重置密码失败',
                  data: [],
              }
              resJson(_res, _data)
          }
      })
      pool.releaseConnection(conn) // 释放连接池，等待别的连接使用
    })
})

 /**
 * 删除用户
 */
 router.delete('/deleteUser', (req, res) => {   
    let params = {
      id:req.query.id
    }
    console.log(params)
    let _res = res;
    let _data;
    // 从连接池获取连接
    pool.getConnection((err, conn) => { //数据库链接
      conn.query(usermanageSQL.deleteUser, [params.id], (e, result) => { //操作数据库
          if (e) _data = {
              code: -1,
              msg: e
          }
          
          if (result && result) {
                _data = {
                    code:0,
                    msg: '删除成功',
                    data: []                   
                }
                resJson(_res, _data)
          } else {
            console.log(e,result)
              _data = {
                  code: -1,
                  msg: '删除失败',
                  data: [],
                  total:0

              }
              resJson(_res, _data)
          }
      })
      pool.releaseConnection(conn) // 释放连接池，等待别的连接使用
    })
})

 /**
 * 查询用户列表
 */
 router.post('/userlist', (req, res) => {   
    let params = {
      limit: req.body.limit || 10,
      page: req.body.page || 1,
      username: req.body.username || '',
      id:req.body.id || '',
    }
    let sql = "SELECT * FROM users";    
    let content = [];
    let isMore = false;//是否有多个查询参数
    if(params.username){
        // 模糊查询两种方法直接在SQL语句后加 mysql.escape("%"+req.body.username+"%")
        // sql += " WHERE username LIKE "+mysql.escape("%"+req.body.username+"%")
        sql += " WHERE username LIKE ?";
        content.push( "%"+params.username+"%" );
        isMore = true;
    }
    if(params.id){
        // 模糊查询两种方法直接在SQL语句后加 mysql.escape("%"+req.body.id+"%")
        // sql += " WHERE id LIKE "+mysql.escape("%"+req.body.id+"%")
        sql += " WHERE id LIKE ?";
        content.push( "%"+params.id+"%" );
        isMore = true;
    }
    if(params.page || params.limit){//开启分页
        let current = params.page;//当前页码
        let pageSize = params.limit;//一页展示多少条数据
        sql += " limit ?, ?";
        content.push((current-1)*pageSize,parseInt(pageSize));
    }
    console.log(params,sql,content)
    let _res = res;
    let _data;
    // 从连接池获取连接
    pool.getConnection((err, conn) => { //数据库链接
      conn.query(sql, content, (e, result) => { //操作数据库
          if (e) _data = {
              code: -1,
              msg: e
          }
          
          if (result && result.length) {
            conn.query(usermanageSQL.selectListAll,(e,res)=>{
                _data = {
                    code:0,
                    msg: '查询成功',
                    data: {
                        list: result,
                        total:res[0]['total']
                    },                    
                }
                resJson(_res, _data)
            })
          } else {
            // console.log(e,result)
              _data = {
                  code: -1,
                  msg: '查询失败',
                  data: [],
                  total:0

              }
              resJson(_res, _data)
          }
      })
      pool.releaseConnection(conn) // 释放连接池，等待别的连接使用
    })
})

module.exports = router;